package es.udc.fic.hamNeggs.web;

import org.apache.log4j.Logger;

import es.udc.fic.hamNeggs.dao.InputCategory;
import es.udc.fic.hamNeggs.dao.InputUser;
import es.udc.fic.hamNeggs.dao.InputUserStory;
import es.udc.fic.hamNeggs.manager.ProjectManager;
import es.udc.fic.hamNeggs.manager.UserManager;
import es.udc.fic.hamNeggs.manager.UserStoriesCategoryManager;
import es.udc.fic.hamNeggs.manager.UserStoriesManager;
import es.udc.fic.hamNeggs.pojo.User;
import es.udc.fic.hamNeggs.pojo.UserStories;
import es.udc.fic.hamNeggs.pojo.UserStories.State;
import es.udc.fic.hamNeggs.pojo.UserStoriesCategory;
import es.udc.fic.hamNeggs.pojo.Works;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;

/**
 * Servlet implementation class UserStoriesDetail
 */
public class UserStoriesDetail extends HttpServlet {
    private static final long   serialVersionUID = 1L;
    private final static Logger LOG              = Logger.getLogger(UserStoriesDetail.class.getName());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserStoriesDetail() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);
        final Long myProject = (Long) session.getAttribute("project");
        final UserStoriesCategoryManager cmtmng = new UserStoriesCategoryManager();

        final ArrayList<InputCategory> categories = new ArrayList<InputCategory>();
        for (final UserStoriesCategory cmt : cmtmng.getCommentList()) {
            final InputCategory category = new InputCategory();
            category.setCategory(cmt);
            categories.add(category);
        }

        cmtmng.close();
        request.setAttribute("categories", categories);
        request.setAttribute("rol", session.getAttribute("rol"));

        if ((request.getParameter("id") != null && request.getParameter("id") != "") || (request.getAttribute("ustid") != null && request.getAttribute("ustid").toString() != "")) {
            final UserStoriesManager ustmng = new UserStoriesManager();
            UserStories ust = null;
            if (request.getParameter("id") != null)
                ust = ustmng.getUserStories(new Long(request.getParameter("id")));
            if (request.getAttribute("ustid") != null)
                ust = ustmng.getUserStories(new Long(request.getAttribute("ustid").toString()));
            final InputUserStory selectUserStory = new InputUserStory();
            selectUserStory.setUserStory(ust);
            request.setAttribute("selectUserStory", selectUserStory);
            ustmng.close();
        }

        final ArrayList<InputUser> iUsers = new ArrayList<InputUser>();
        final ProjectManager prjmng = new ProjectManager();
        for (final Works w : prjmng.getProject(myProject).getWorker()) {
            final InputUser user = new InputUser();
            user.setUser(w.getUser());
            user.setCurrentRol(w.getRol().getString());
            iUsers.add(user);
        }
        prjmng.close();
        request.setAttribute("users", iUsers);

        request.getRequestDispatcher("/user_stories_detail.jsp").forward(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);

        final Long myProject = (Long) session.getAttribute("project");

        final UserStoriesManager ustmng = new UserStoriesManager();
        final UserManager usrmng = new UserManager();
        final UserStoriesCategoryManager catmng = new UserStoriesCategoryManager();
        final ProjectManager prjmgn = new ProjectManager();

        try {
            switch (request.getParameter("action")) {
                case "Add":
                    final InputUserStory story = new InputUserStory();

                    if (request.getParameter("name") != null)
                        story.setName(request.getParameter("name"));
                    if (request.getParameter("description") != null)
                        story.setDescription(request.getParameter("description"));
                    if (request.getParameter("estimatedstoryPoints") != null)
                        story.setEstimatedstoryPoints(request.getParameter("estimatedstoryPoints"));
                    if (request.getParameter("category") != null)
                        story.setCategory(request.getParameter("category"));

                    final UserStories newStory = story.toUserStory();
                    newStory.setCreationDate(new Date(Calendar.getInstance().getTimeInMillis()));
                    newStory.setProject(prjmgn.getProject(myProject));
                    newStory.setState(State.Created);
                    ustmng.saveUserStories(newStory);

                    break;
                case "Update":
                    final UserStories oldStoryu = ustmng.getUserStories(new Long(request.getParameter("ustid")));
                    if (request.getParameter("category") != null && !request.getParameter("category").equals(""))
                        oldStoryu.setUserStoriesCategory(catmng.getUserStoriesCategory(new Long(request.getParameter("category"))));
                    if (request.getParameter("description") != null && !request.getParameter("description").equals(""))
                        oldStoryu.setDescription(request.getParameter("description"));
                    if (request.getParameter("estimatedstoryPoints") != null && !request.getParameter("estimatedstoryPoints").equals(""))
                        oldStoryu.setEstimatedstoryPoints(new Integer(request.getParameter("estimatedstoryPoints")));
                    if (request.getParameter("name") != null && !request.getParameter("name").equals(""))
                        oldStoryu.setName(request.getParameter("name"));
                    ustmng.updateUserStories(oldStoryu);
                    break;
                case "AddCategory":
                    final UserStoriesCategory category = new UserStoriesCategory();
                    category.setCategory(request.getParameter("name"));
                    catmng.saveUserStoriesCategory(category);
                    break;
                case "UpdateCategory":
                    final UserStoriesCategory categoryu = catmng.getUserStoriesCategory(new Long(request.getParameter("catid")));
                    if (request.getParameter("name") != null && !request.getParameter("name").equals(""))
                        categoryu.setCategory(request.getParameter("name"));
                    catmng.updateUserStoriesCategory(categoryu);
                    break;
                case "DeleteCategory":
                    final UserStoriesCategory categoryd = catmng.getUserStoriesCategory(new Long(request.getParameter("catid")));
                    catmng.deleteUserStoriesCategory(categoryd);
                    break;
                case "Assign":
                    final String ustid = request.getParameter("ustid");
                    final UserStories ust = ustmng.getUserStories(new Long(ustid));
                    final User usr = usrmng.getUser(new Long((Long) session.getAttribute("user")));
                    ust.setUser(usr);
                    usr.setOneUserStories(ust);
                    ustmng.updateUserStories(ust);
                    break;
                case "AssignTo":
                    final String ustidt = request.getParameter("ustid");
                    final UserStories ustt = ustmng.getUserStories(new Long(ustidt));
                    final User usrt = usrmng.getUser(new Long(request.getParameter("user")));
                    ustt.setUser(usrt);
                    usrt.setOneUserStories(ustt);
                    ustmng.updateUserStories(ustt);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            String error = "[";
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                final String paramName = names.nextElement();
                final String paramValue = request.getParameter(paramName);
                error = error.concat(paramName + ":" + paramValue + ";");
            }
            error = error.concat("]");
            LOG.error("Error while executing action: " + request.getParameter("action")
                    + "with params: " + error + "\n"
                    , e);
        }

        ustmng.close();
        usrmng.close();
        catmng.close();
        prjmgn.close();

        request.setAttribute("ustid", request.getParameter("ustid").toString());
        doGet(request, response);
    }

}
